package com.sunyard.manage.controller;


import com.sunyard.constant.ErrMessageConst;
import com.sunyard.dal.bo.*;
import com.sunyard.dal.bo.device.*;
import com.sunyard.dal.bo.device.key.KeyUploadLogBO;
import com.sunyard.dal.bo.task.OrgBO;
import com.sunyard.dal.bo.task.SingleLockBo;
import com.sunyard.dal.dto.TerminalCopyDTO;
import com.sunyard.dal.dto.TerminalCopyReslutDTO;
import com.sunyard.dal.dto.TerminalDTO;
import com.sunyard.dal.dto.TerminalQueryResDTO;
import com.sunyard.dal.dto.znsTask.OrgDTO;
import com.sunyard.dal.dto.znsTask.OperatorDTO;
import com.sunyard.dal.entity.Terminal;
import com.sunyard.dal.entity.TerminalCopy;
import com.sunyard.enums.TerminalTypeEnum;
import com.sunyard.manage.service.TerminalService;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.manage.DataGrid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Api(tags = "TerminalController", description = "终端管理")
@Slf4j
@RestController
@RequestMapping(value = "/treminal", method = RequestMethod.POST)
public class TerminalController {

    @Autowired
    private TerminalService terminalService;

    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("分页查询终端信息")
    public BaseResult<DataGrid<TerminalQueryResDTO>> getTerminalByPage(@RequestBody PaginationBO<TerminalQueryBO> queryBO, HttpServletRequest request) {
        try {
            resetLock(request);
            return terminalService.getTerminalByPage(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/queryByMac", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("根据mac查询设备信息")
    public BaseResult<TerminalQueryResDTO> getTerminalByMac(@RequestBody TerminalMacBO terminalMacBO, HttpServletRequest request) {
        return terminalService.getTerminalByMac(terminalMacBO, request);
    }

    @RequestMapping(value = "/addTerminal", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增终端信息")
    public BaseResult addTerminal(@Validated @RequestBody TerminalAddBO addBO, HttpServletRequest request) {
        try {
            return terminalService.addTerminal(addBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/updateTerminal", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("修改终端信息")
    public BaseResult updateTerminal(@Validated @RequestBody TerminalUpdateBO updateBO, HttpServletRequest request) {
        try {
            return terminalService.updateTerminal(updateBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/deleteTerminal", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("删除终端信息")
    public BaseResult deleteTerminal(@Validated @RequestBody TerminalDeleteBO deleteBO, HttpServletRequest request) {
        try {
            return terminalService.deleteTerminal(deleteBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/initLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("锁具初始化")
    public BaseResult initLock(@Validated @RequestBody TerminalInitBO initBO, HttpServletRequest request) {
        try {
            return terminalService.initLock(initBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/batchDeleteTerminal", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("批量删除终端信息")
    public BaseResult batchDeleteTerminal(@Validated @RequestBody TerminalBatchDeleteBO deleteBO, HttpServletRequest request) {
        try {
            return terminalService.batchDeleteTerminal(deleteBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/sign", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("钥匙签到")
    public BaseResult sign(@Validated @RequestBody TerminalSignBO signBO, HttpServletRequest request) {
        try {
            return terminalService.sign(signBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/updateState", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("终端启用和停用")
    public BaseResult updateState(@Validated @RequestBody TerminalUpdateStateBO updateStateBO, HttpServletRequest request) {
        try {
            return terminalService.updateState(updateStateBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/batchUpdateState", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("终端批量启用和停用")
    public BaseResult batchUpdateState(@Validated @RequestBody TerminalBatchUpdateStateBO updateStateBO, HttpServletRequest request) {
        try {
            return terminalService.batchUpdateState(updateStateBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/exportTerminal", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("终端信息导出")
    public BaseResult exportTerminal(@RequestBody PaginationBO<TerminalQueryBO> queryBO, HttpServletRequest request, HttpServletResponse response) {
        try {
            return terminalService.exportTerminal(queryBO, request, response);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/queryAuditInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("分页查询审核终端信息")
    public BaseResult<DataGrid<TerminalCopyReslutDTO>> queryAuditInfo(@RequestBody PaginationBO<TerminalCopyDTO> queryBO, HttpServletRequest request) {
        try {
            return terminalService.queryAuditInfo(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 指纹审核导出
     * @Author: tsz
     */
    @ApiOperation("终端审核导出")
    @RequestMapping(value = "/terminalAuditExport")
    @ResponseBody
    public void terminalAuditExport(HttpServletResponse response, @RequestBody TerminalCopyDTO terminalCopyDTO, HttpServletRequest request) {
        terminalService.terminalAuditExport(response,terminalCopyDTO,request);
    }


    @RequestMapping(value = "/selectAuditInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("查询审核详情")
    public BaseResult<Map<String, TerminalCopy>> selectAuditInfo(@RequestBody TerminalCopyDTO queryBO, HttpServletRequest request) {
        try {
            return terminalService.selectAuditInfo(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("审核")
    public BaseResult<TerminalCopy> audit(@RequestBody TerminalCopyDTO queryBO, HttpServletRequest request) {
        try {
            return terminalService.audit(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/batchAudit", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("批量审核")
    public BaseResult<TerminalCopy> batchAudit(@RequestBody TerminalAuditBO auditBO, HttpServletRequest request) {
        try {
            return terminalService.batchAudit(auditBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * 下载导入模板xls
     */
    @ApiOperation("下载导入模板xls")
    @PostMapping("/downloadTem")
    public void downloadTem(HttpServletResponse response, @RequestBody TerminalDTO terminalDTO) {
        String[] headers = new String[7];
        if ("0".equals(terminalDTO.getType())) {
            headers = new String[]{"终端名称", "钥匙种类(1指纹钥匙 2物联网钥匙 3动码钥匙 4金库钥匙)", "所属机构号", "mac地址", "是否超出电子围栏使用(1否2是)", "备注"};
        } else if ("1".equals(terminalDTO.getType())) {
            headers = new String[]{"终端名称", "锁种类(1通用锁 2员工单锁 )", "所属机构号", "锁场景", "柜员编号", "日志翻转(1-不翻转，2-翻转)", "是否跳梁锁(0-否，1-是)", "备注"};
        } else if ("2".equals(terminalDTO.getType())) {
            headers = new String[]{"终端名称", "所属机构号", "尾箱种类(0物联网尾箱/1普通尾箱)", "尾箱imei号", "电子标签id", "尾箱场景", "尾箱状态(0在途/1在网点/2在金库)", "尾箱编号", "是否超出电子围栏使用(1否2是)", "备注", "绑定锁id1", "绑定锁id2"};
        } else if (TerminalTypeEnum.PDA.getCode().equals(terminalDTO.getType())) {
            headers = new String[]{"终端名称", "所属机构号", "imei号", "PDA类型(0-手机/1-掌机)", "PDA编号", "是否超出电子围栏使用(1否2是)", "备注"};
        } else if (TerminalTypeEnum.RFID.getCode().equals(terminalDTO.getType())) {
            headers = new String[]{"终端名称", "所属机构号", "设备编号", "备注"};
        }
        List<Object[]> dataList = null;
        // 防止中文乱码
        String headStr = null;
        OutputStream out = null;
        try {
            headStr = "attachment; filename=\"" + new String("customerMangerTemplate.xls".getBytes("utf8"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput("customerMangerTemplate.xls", headers, dataList);
            ex.export(out);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "/importInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("导入设备数据")
    @Transactional
    public BaseResult importInfo(HttpServletRequest request, TerminalCopyDTO terminalDTO, @RequestParam("multipartFile") MultipartFile multipartFile) {
        try {
            return terminalService.importInfo(request, terminalDTO, multipartFile);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/selectCount", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("查询未审核的设备数量")
    public BaseResult<Integer> selectCount(@RequestBody TerminalDTO dto, HttpServletRequest request) {
        try {
            return terminalService.selectCount(dto, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/uploadLog", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("上传操作日志")
    public BaseResult uploadLog(@Validated @RequestBody KeyUploadLogBO uploadLogBO, HttpServletRequest request) {
        try {
            return terminalService.uploadLog(uploadLogBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/track", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("尾箱追踪")
    public BaseResult<Terminal> track(@RequestBody TerminalDTO dto, HttpServletRequest request) {
        try {
            return terminalService.track(dto, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/switch", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("门磁开关")
    public BaseResult openSwitch(@RequestBody TerminalDTO dto, HttpServletRequest request) {
        try {
            return terminalService.openSwitch(dto, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/openTwo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("锁状态2")
    public BaseResult openTwo(@RequestBody TerminalDTO dto, HttpServletRequest request) {
        try {
            return terminalService.openTwo(dto, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/openThree", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("门状态1")
    public BaseResult openThree(@RequestBody TerminalDTO dto, HttpServletRequest request) {
        try {
            return terminalService.openThree(dto, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/saveTrunkData", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("接收尾箱数据接口")
    public BaseResult saveTrunkData(@RequestBody TerminalDTO dto, HttpServletRequest request) {
        try {
            return terminalService.saveTrunkData(dto, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/selectLockAll", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("查询所有锁信息")
    public BaseResult<List<Terminal>> selectLockAll(HttpServletRequest request) {
        try {
            return terminalService.selectLockAll(request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/getOperateBySn", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("根据sn码获取柜员列表")
    public BaseResult<List<OrgDTO>> getOperateBySn(HttpServletRequest request, @RequestBody @Validated TerminalSnBO terminalSnBO) {
        try {
            return terminalService.getOperateBySn(request, terminalSnBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/getData", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("获取物联网平台尾箱数据")
    public BaseResult getData(HttpServletRequest request) {
        try {
            return terminalService.getDate(request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * 该接口实现查询调拨锁是否已经过期，如果已经过期，则还原改锁原来机构
     *
     * @param request 二期改接口可以改成定时任务
     * @return BaseResult
     **/
    @RequestMapping(value = "/resetLock", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("还原调拨锁所属机构")
    public BaseResult resetLock(HttpServletRequest request) {
        try {
            return terminalService.resetLock();
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/checkKey", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("钥匙合法性校验")
    public BaseResult checkKey(@Validated @RequestBody TerminalSignBO signBO, HttpServletRequest request) {
        try {
            return terminalService.checkKey(signBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }


    @PostMapping("/findOperatorByOrg")
    @ApiOperation("根据机构查询开锁权限人员列表")
    public BaseResult<List<OperatorDTO>> findOperatorByOrg(@RequestBody OrgBO orgBO, HttpServletRequest request) {
        return terminalService.findOperatorByOrg(orgBO,request);
    }

    @PostMapping("/findOperatorByOrgAndTaskType")
    @ApiOperation("根据机构和任务场景查询开锁权限人员列表")
    public BaseResult<List<OperatorDTO>> findOperatorByOrgAndTaskType(@RequestBody SingleLockBo singleLockBo, HttpServletRequest request) {
        return terminalService.findOperatorByOrgAndTaskType(singleLockBo,request);
    }

    @PostMapping("/getCurrentTime")
    @ApiOperation("获取当前系统时间")
    public BaseResult getCurrentTime() {
        return terminalService.getCurrentTime();
    }

}
